from rest_framework import serializers
from .models import Article, Column, Topic

from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email']

class ColumnSerializer(serializers.ModelSerializer):
    class Meta:
        model = Column
        fields = ['id', 'name', 'slug', 'description', 'order']



# 新增专题序列化器
class TopicSerializer(serializers.ModelSerializer):
    class Meta:
        model = Topic
        fields = ['id', 'name', 'slug', 'description', 'cover_image', 'created_at']

class ArticleSerializer(serializers.ModelSerializer):
    column = ColumnSerializer(read_only=True)
    author = UserSerializer(read_only=True)
    column_id = serializers.PrimaryKeyRelatedField(queryset=Column.objects.all(), write_only=True, source='column')
    author_id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), write_only=True, source='author')
    topics = TopicSerializer(read_only=True)
    topics_id = serializers.PrimaryKeyRelatedField(queryset=Topic.objects.all(), write_only=True, source='topics', required=False, allow_null=True)

    class Meta:
        model = Article
        fields = [
            'id', 'title', 'column', 'column_id', 'topics', 'topics_id', 'redirect_url', 'is_recommended', 'status', 
            'author', 'author_id', 'publish_date', 'update_date', 'keywords', 
            'cover_image', 'content'
        ]
        read_only_fields = ['publish_date', 'update_date']
